<template>
  <div>
    <h1>{{ id ? "编辑" : "新建" }}广告</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item label="添加一条广告">
        <el-button
          size="small"
          type="primary"
          @click="model.items.push({})"
          icon="el-icon-plus"
          ></el-button
        >
      </el-form-item>
      <el-row>
        <el-col :md="12" v-for="(item, index) in model.items" :key="index">
          <el-form-item :label="'图片标题' + (index+1)">
            <el-input v-model="item.title"></el-input>
          </el-form-item>
          <el-form-item label="跳转连接">
            <el-input v-model="item.url"></el-input>
          </el-form-item>
          <el-form-item label="图片">
            <el-upload
              class="avatar-uploader"
              :action="$http.defaults.baseURL + 'upload'"
              :show-file-list="false"
              :on-success="(res) => $set(item, 'image', res.url)"
            >
              <img v-if="item.image" :src="item.image" class="avatar w-100" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button
              type="danger"
              round
              size="mini"
              @click="model.items.splice(index, 1)"
              icon="el-icon-delete"
            ></el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" native-type="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: {}
  },
  data () {
    return {
      model: {
        items: []
      }
    }
  },
  methods: {
    // 保存广告
    async save () {
      if (!this.model.name) return this.$message({ type: 'error', message: '请填写数据' })

      if (this.id) {
        // 如果传入了id就发送编辑广告名称的请求
        await this.$http.put(`rest/ads/${this.id}`, this.model)
      } else {
        // 没有id就是发送创建广告名称
        await this.$http.post('rest/ads', this.model)
      }
      this.$router.push('/ads/list')
      this.$message({
        type: 'success',
        message: '保存成功'
      })
    },
    // 编辑广告
    async fetch () {
      const res = await this.$http.get(`rest/ads/${this.id}`)
      this.model = res.data
    }
  },
  created () {
    this.id && this.fetch()
  }
}
</script>

<style scoped>

</style>
